using System.ComponentModel;
using System.Data;
using System.Dynamic;
using System.Reflection;
using Newtonsoft.Json.Serialization;

namespace SB2.Core;

public static class DtoExtends
{
    /// <summary>
    /// 获取枚举的描述信息
    /// </summary>
    /// <param name="em"></param>
    /// <returns></returns>
    public static string GetDescription(this Enum em)
    {
        Type type = em.GetType();
        var fd = type.GetField(em.ToString());
        string des = fd.GetDescription();
        return des;
    }
    /// <summary>
    /// 获取属性的描述信息
    /// </summary>
    public static string GetDescription(this Type type, string proName)
    {
        PropertyInfo pro = type.GetProperty(proName);
        string des = proName;
        if (pro != null)
        {
            des = pro.GetDescription();
        }
        return des;
    }
    /// <summary>
    /// 转json字符串
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string ToJson(this object obj)
    {
        return JSON.Serialize(obj);
    }
    /// <summary>
    /// dateTable 转 Dynamic
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static List<dynamic> ToDynamic(this DataTable dt)
    {
        var dynamicDt = new List<dynamic>();
        foreach (DataRow row in dt.Rows)
        {
            dynamic dyn = new ExpandoObject();
            dynamicDt.Add(dyn);
            foreach (DataColumn column in dt.Columns)
            {
                var dic = (IDictionary<string, object>)dyn;
                dic[column.ColumnName] = row[column];
            }
        }
        return dynamicDt;
    }
    /// <summary>
    /// json字符串序列化
    /// </summary>
    /// <param name="json"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static T ToObject<T>(this string json)
    {

        return JSON.Deserialize<T>(json);
    }
    /// <summary>
    /// 获取属性的描述信息
    /// </summary>
    public static string GetDescription(this MemberInfo info)
    {
        var attrs = (DescriptionAttribute[])info.GetCustomAttributes(typeof(DescriptionAttribute), false);
        string des = info.Name;
        foreach (DescriptionAttribute attr in attrs)
        {
            des = attr.Description;
        }
        return des;
    }

}